package com.source.lightfowl.utils;

import com.source.lightfowl.constant.ImageCatalogue;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.util.UUID;

/**
 * @Author: xcy
 * @Date:Create：in 2020/9/27 22:04
 * @Description: 保存图片到服务器的工具类（需要在配置类里配置路径影射）
 */

public class ImageUtil {

    public static final String IMAGE_PATH= File.separator+"usr"+ File.separator+"local"+ File.separator+"image"+File.separator;


    /**
     *  说明： 调用这个方法 需要传递图片（file,multipartFile）作为参数  这个方法会把图片保存在/usr/local/image目录下面 然后返回一个虚拟路径 这个路径需要存在数据库 前端取出这个路径就可以访问到图片
     *
     * @param  （file）
     * @return 返回的是保存在数据库的相对路径
     */
    public static String saveImage(MultipartFile mfile, ImageCatalogue catalogue) throws Exception {
        File upload = ImageUtil.multipartFileToFile(mfile);
        //处理上传的文件
        String fileName = sava(upload,catalogue);
        //6.返回图片名字
        return "/image/"+catalogue.getCatalogue()+"/"+fileName;
    }
    /*
    重载
     */
    public static String saveImage(File upload ,ImageCatalogue catalogue){
        //处理上传的文件
        String fileName = sava(upload,catalogue);
        //6.返回图片名字
        return "/image/"+catalogue.getCatalogue()+"/"+fileName;
    }
    //保存图片 并返回一个虚拟路径 保存到数据库
    private static String sava(File upload,ImageCatalogue catalogue) {
        String fileName = "";
        if(upload!=null){
            //1.获取文件扩展名
            String uploadFileName = upload.getName();
            int index = uploadFileName.lastIndexOf(".");
            String exName = uploadFileName.substring(index);
            //2.随机生成文件名
            //String uuid = UUID.randomUUID().toString();
            String uuid = UUID.randomUUID().toString().substring(0,8);
            //3.拼接扩展名
            fileName = uuid + exName;
            //4.生成服务器文件位置
            File imagePath = new File(ImageUtil.IMAGE_PATH+catalogue.getCatalogue());
            if (!imagePath.exists()){
                imagePath.mkdirs();
            }
            File file = new File(ImageUtil.IMAGE_PATH+catalogue.getCatalogue()+ File.separator+fileName);
            try {
                //5.复制图片
                Files.copy(upload.toPath(),file.toPath());
                System.out.println("图片保存成功");
            } catch (IOException e) {
                System.out.println("商品图片保存异常");
            }
        }
        return fileName;
    }

    //文件格式的转换
    public static File multipartFileToFile(MultipartFile file ) throws Exception {

        File toFile = null;
        if(file.equals("")||file.getSize()<=0){
            file = null;
        }else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }

        return toFile;

    }

    //删除图片
    public static void delete(String path,ImageCatalogue catalogue){
        //
        String[] split = path.split("/");
        String name = split[split.length - 1];
        File file = new File(IMAGE_PATH + catalogue.getCatalogue()+"/"+name);
        try {
            Files.delete(file.toPath());
        } catch (IOException e) {
            System.out.println("删除图片出错");
            e.printStackTrace();
        }

    }


    //下面的两个方法暂时用不到
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void getImage(String name, HttpServletResponse response){
        File file = new File(ImageUtil.IMAGE_PATH+ File.separator+name);
        response.setContentType("image/png"); // 不同文件的MimeType参考后续链接
        // 读取路径下面的文件
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            //创建字节对象
            byte[] buffer;
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream(fis.available());
            byte[] bytes = new byte[fis.available()];
            int temp;
            while ((temp = fis.read(bytes)) != -1) {
                baos.write(bytes, 0, temp);
            }
            fis.close();
            baos.close();
            buffer = baos.toByteArray();

            outputStream.write(buffer);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
